<template>
	<view class="app" style="padding-bottom: 110rpx">
		<uni-nav-bar fixed left-icon="back" title="确认订单" @clickLeft="clickLeft()"></uni-nav-bar>

		<view class="row-mg" style="padding: 0">
			<view class="tab-box">
				<view class="tab-item x-c" :style="loginWay == 0 ? 'background: #fff':''" @tap="onLoginWay(0)">
					<text class="tab-title" :style="loginWay == 0 ? 'color:#6CB041': ''">店内自提</text>
					<view class="line-box" password v-show="loginWay === 0"></view>
				</view>
				<!--<view class="tab-item x-c" @tap="onLoginWay(1)" :style="loginWay == 1 ? 'background: #fff':''">
					<text class="tab-title" :style="loginWay == 1 ? 'color:#6CB041': ''">配送</text>
					<view class="line-box" v-show="loginWay === 1"></view>
				</view>-->
			</view>
			<view class="tab-chg" v-if="loginWay == 0">
				<view class="tui-flex bdr-bot" @tap="isShow = !isShow">
					<view class="tit">自提时间：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.pickTime"
							   disabled
							   class="uni-easyinput"
							   placeholder="选择时间">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
				<view class="tui-flex">
					<view class="tit">预留手机号：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.phone" placeholder="请输入手机号" class="uni-easyinput">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
			</view>
			<view class="tab-chg" v-else>
				<view class="tui-flex bdr-bot" @tap="navTo('/pages/perform/address?source=1')">
					<view class="address" v-if="addressList.length">
						<view>{{addressData.address}}</view>
						<view class="text">
							<text>{{addressData.contactName}}</text>
							<text class="tui-pd-left">{{addressData.contactPhone}}</text>
						</view>
					</view>
					<view class="address" v-else>
						请选择地址
					</view>
					<view style="width:8%;text-align: right;">
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
				<view class="tui-flex bdr-bot" @tap="isDisShow = !isDisShow">
					<view class="tit">配送时间：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.distributionTime"
							   disabled
							   class="uni-easyinput" placeholder="选择时间">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<view class="c_box">
			<view v-for="(item ,index) in list.data" :key="index" class="tui-flex flex">
				<view class="c_img">
					<image :src="item.pic" mode="aspectFill"></image>
				</view>
				<view class="c_content">
					<view class="c_name">{{item.productName}}</view>
					<view class="c_name">￥{{item.price}}</view>
					<view class="c_num">数量: x{{item.num}}</view>
				</view>
			</view>
			<view class="num-bot" style="font-size: 30rpx">
				<view>总额：<text style="color: #FF6666;">￥{{money}}</text></view>
			</view>
		</view>
		<view class="c_box">
			<view class="tui-flex pad">
				<view class="tit">买家留言：</view>
				<view class="ipt">
					<textarea @blur="bindTextAreaBlur" auto-height placeholder="买家留言" style="width: 100%;text-align: right"/>
				</view>
			</view>
		</view>
		<view class="c_box">
			<view class="tui-flex pad" @tap="showModal = !showModal">
				<view class="tit">优惠券</view>
				<view class="ipt uni-easyinput" :style="{color:couponText != '暂无优惠券'?'#FF6666':'#999'}">
					<text>{{couponText}}</text>
				</view>
				<view>
					<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
				</view>
			</view>
			<view class="tui-flex pad">
				<view class="tit">
					余额(<text style="font-size: 28rpx;color: #FF6666">
						￥{{walletBalance}}
					</text>)
				</view>
				<view class="ipt uni-easyinput">
					<text style="color: #FF6666">-￥{{Balance}}</text>
				</view>
			</view>
			<view class="num-bot">
				<view>小计：<text style="color: #FF6666;">￥{{totalAmount}}</text></view>
			</view>
		</view>

		<!--按钮-->
		<pay-btn :amount="totalAmount"
				 payText="提交订单"
				 title="总计"
				 @imPayment="imPayment(list)">
		</pay-btn>

		<time-alert title="自提时间"
					rangeStartTime="8:00:00"
					rangeEndTime="21:00:00"
					subhead=''
					rangeDay="2"
					disabled="0,2"
					:isShow="isShow"
					:isNow="isNow"
					@closeAlert="handelClose">
		</time-alert>

		<time-alert
				title="配送时间"
				subhead=""
				rangeStartTime="8:00:00"
				rangeEndTime="21:00:00"
				intervalTime="30"
				dayStartIntTime="20"
				rangeDay="5"
				disabled="0,2"
				:isShow="isDisShow"
				:isNow="isNow"
				:maskHide="maskHide"
				:rangeType="rangeType"
				@closeAlert="handelDisClose"
		></time-alert>

		<coupon-modal :isShow="showModal"
					  :list="listData"
					  :money="money"
					  :businId="businList"
					  @closeAlert="handeClose"
					  @closeBtnClose="showModal = !showModal"
		></coupon-modal>

		<!-- 登录提示 -->
		<uni-login-model></uni-login-model>
	</view>
</template>

<script>
    import uniIcons from "@/components/uni-icons/uni-icons.vue"
    import payBtn from '@/components/payBtn/index'
    import timeAlert from '@/components/time-alert/time-alert.vue'
    import couponModal from '@/components/coolc-coupon/coupon-modal.vue'
    import { mapState } from 'vuex'
    import uniLoginModel from '@/components/uni-login-model/uni-login-model.vue'

	export default {
		components: {
            uniIcons, payBtn, timeAlert, couponModal, uniLoginModel
		},
		data() {
			return {
				list: [],
                listData: [],
				money: 0,
                loginWay: 0,
                isShow: false,
                isNow: false,
                isDisShow: false,
                maskHide: false,
                showModal: false,
                rangeType: true,
                listFrom: {
                    phone: '',
                    pickTime: '',
                    distributionTime: '',
                    num: 1,
                    buyerMessage: '',
                },
                addressData: {
                    contactName: undefined,
                    contactPhone: undefined,
                    userId: undefined,
                    address: undefined,
                    default: undefined,
                },
                editFrom: {},
				couponData: {},
				totalAmount: 0,
                couponText: '暂无优惠券',
                walletBalance: 0,
                Balance: 0,
                businList:[]
			};
		},
        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo
            })
        },
		onLoad(option) {
		    this.walletBalance = this.userInfo.walletBalance
			this.list = JSON.parse(option.data)
            this.money = this.list.money
            let num = 0
            if (this.walletBalance>this.list.money) {
			    let balance = 0;
                balance  = this.walletBalance - (this.walletBalance - this.list.money)
                this.Balance = Number(balance.toFixed(2))
			} else {
                num  = this.list.money - this.walletBalance
                this.Balance = this.walletBalance
			}
            this.totalAmount = Number(num.toFixed(2))
			if (this.totalAmount <=0) {
                this.totalAmount = 0
			}
			this.loadData()
		},
		methods: {
			//确认支付
            imPayment(item) {
                console.log(item.data)
                var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
				if (!this.listFrom.phone) {
                 	this.$api.msg('手机号不能为空')
                	return;
				} else if (!myreg.test(this.listFrom.phone)) {
                  	uni.showModal({ content: '手机号不正确', showCancel: false });
                  	return;
				}
				let bindShopIds;
                if (JSON.stringify(this.couponData)!='{}'){
                    if (this.couponData.useConditionType != 'NONE') {
                        bindShopIds = this.couponData.bindShopIds[0]
                    }
				}
                this.editFrom = {
                    ...this.editFrom,
                    productType: 1,
                    couponId: this.couponData.couponId,
                    shopId: bindShopIds,
					balance: this.Balance,
                    totalAmount:this.money,
                    actAmount:this.totalAmount,
                    cartProductDtoList: item.data,
                    ownSpec:JSON.stringify(this.listFrom),
                }
                this.$api.api('order.create', this.editFrom).then(res => {
                    uni.hideLoading();
                    if (res.code == 200) {
                        this.$wx.miniProgram.reLaunch({
                            url: `/pages/pay/pay?money=${this.totalAmount}&orderNo=${res.data.orderNo}&productType=1`,
                            success: function(res){
                                console.log(res)
                            },
                            fail: function(err){
                                console.log(err)
                            },
                        });
                    } else {
                        this.$api.msg(res.message)
                    }
                }).catch(error => {
                    this.$api.msg(error.message)
                })
			},
            bindTextAreaBlur: function (e) {
                this.listFrom.buyerMessage = e.detail.value
            },
            handelClose(data) {
                this.isShow = false;
                this.listFrom.pickTime = data._date
            },
            handeClose(data) {
                this.showModal = false
				this.couponData = data
                if (data.faceValue == 0) {
                    this.couponText = data.name
                } else {
                    this.couponText = '-￥'+data.faceValue
                }
                let num = 0
                if (data.faceValue>=this.list.money) {
                    this.Balance = 0
                    let number1 = data.faceValue - this.list.money
                    this.totalAmount = Number(number1.toFixed(2))
                } else if (this.walletBalance>this.list.money) {
                    let money  = this.walletBalance -(this.walletBalance - this.list.money) - data.faceValue
                    num = Number(money.toFixed(2))
                    this.Balance = num
                } else {
                    this.Balance = this.walletBalance
                    num  = this.list.money - data.faceValue - this.Balance
                    this.totalAmount = Number(num.toFixed(2))
                }
                if (this.totalAmount <= 0) { this.totalAmount = 0 }
            },
            //	获取优惠券列表
            loadData() {
                uni.showLoading()
                this.$api.api('coupon.list', {status: 0}).then(res => {
                    uni.hideLoading();
                    if (res.code == 200 ){
                        this.listData = res.data
                        for (var i = 0, lenI = this.listData.length; i < lenI; ++i) {
                            this.listData[i].couponId = String(this.listData[i].couponId)
                        }
                        let list = [],obj=[],matched;
						this.list.data.forEach(i => {
						    obj.push(i.businId);
						    this.businList.push(i.businId)
						})
						
						// 判断优惠券是否满足要求
						let flag = false;
						
						/* tanyi update 2021-12-10*/
						for (let i in res.data) {
							// 1. 优惠券所属门店 == 当前门店
							obj.forEach(i => {
							    return matched = item.bindShopIds.find((value) => value == i);
							});
							
							if(Object.keys(matched).length==0){
								console.log("门店不匹配")
								continue;
							}
							
							// 2. 优惠券金额 < 当前交易金额
							if (res.data[i].useConditionType == 'FULL_REDUCTION' && res.data[i].useConditionValue < this.money) {
								console.log("优惠券金额>当前订单金额")
								continue;
							}
							
							list.push(res.data[i])
							this.couponText = `有${list.length}张可用`
							this.listData = list
							flag = true;
							
						}
						
						if (!flag) {
							this.listData = [];
						}
						
                        /* res.data.forEach(item => {
                            obj.forEach(i => {
                                return matched = item.bindShopIds.find((value) => value == i);
                            });
                            if (item.useConditionType == 'NONE' || (item.useConditionType == 'FULL_REDUCTION' && this.money > item.useConditionValue && matched)){
                                list.push(item)
								this.couponText = `有${list.length}张可用`
                                this.listData = list
							} else {
                                this.listData = []
							}
						}) */
                    } else {
                        uni.showToast({title: res.message, icon: 'none'})
                    }
                }).catch(error => {
                })
            },
            navTo(url) {
                uni.navigateTo({url:url})
            }
		}
	}
</script>

<style lang='scss' scoped>
	.row-mg {
		margin: 30rpx;
		background: #fff;
		border-radius: 15rpx;
		padding: 0 30rpx;
	}
	.tab-box {
		display: flex;
		.tab-item {
			flex: 1;
			height: 80rpx;
			position: relative;
			background: #6cb041bd;
			border-radius: 15rpx 0 0 0;
			transition: 0.3s;
			&:last-child {
				border-radius: 0 15rpx 0 0;
			}
			.tab-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #fff;
				margin-bottom: 10rpx;
			}
			.line-box {
				position: absolute;
				width: 120rpx;
				height: 4rpx;
				background: #6CB041;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
	.tab-chg {
		padding: 26rpx;
		.bdr-bot {
			padding-bottom: 15rpx;
		}
	}
	.tit {
		width: 32%;
		font-size: 32rpx;
	}
	.ipt {
		flex: 1;
	}
	.uni-easyinput {
		text-align: right;
		font-size: 32rpx;
	}

.c_box {
	background: #fff;
	margin: 20rpx;
	border-radius: 15rpx;
	padding: 20rpx;
	.flex {
		padding-bottom: 25rpx;
	}
	.c_img {
		width: 25%;
		height: 140rpx;
		image {
			width: 100%;
			height: 100%;
			border-radius: 10rpx;
		}
	}
	.c_content {
		flex: 1;
		padding-left: 20rpx;
		.c_name {
			font-size: 30rpx;
		}
		.c_num {
			color: #999;
		}
	}
	.pad{
		padding: 10rpx 0;
		border-bottom: 2rpx dashed #eee;
		&:last-child{
			border-bottom: 0;
		}
	}
}
	.num-bot {
		font-size: 40rpx;
		text-align: right;
		padding-top: 10rpx;
	}
</style>
